package com.xilada.xldutils.fragment;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.xilada.xldutils.R;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.bean.Image;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 */
public class ImageGridFragment extends BaseFragment{

    private List<Image> images = new ArrayList<>();
    private BaseRecyclerAdapter<Image> imageAdapter ;
    private static final int LOADER_ALL = 0;
    private static final int LOADER_CATEGORY = 1;
    private boolean hasFolderGened = false;
    private int itemWidth = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        itemWidth = mScreenWidth/4;

        RecyclerView mRecyclerView = findViewById(R.id.mRecyclerView);

        imageAdapter = new BaseRecyclerAdapter<Image>(images, R.layout.item_image_grid) {
            @Override
            public void onBind(int position, Image image, ViewHolder holder) {
                SimpleDraweeView draweeView = holder.bind(R.id.image);
                Uri uri = Uri.parse("file://"+image.path);
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setLocalThumbnailPreviewsEnabled(true)
                        .setAutoRotateEnabled(true)
                        .setResizeOptions(new ResizeOptions(itemWidth,itemWidth))
                        .build();

                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
//                        .setUri(uri)
                        .setOldController(draweeView.getController())
                        .build();
//                DraweeController controller = Fresco.newDraweeControllerBuilder()
//                        .setUri(uri)
//                        .setOldController(draweeView.getController())
//                        .build();
//                draweeView.getLayoutParams().width = itemWidth;

                draweeView.setController(controller);
            }
        };
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(imageAdapter);

        getActivity().getSupportLoaderManager().initLoader(LOADER_ALL, null, mLoaderCallback);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_image_grid,container,false);
    }

    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media._ID };

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if(id == LOADER_ALL) {
                return new CursorLoader(getActivity(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                        IMAGE_PROJECTION[4]+">0 AND "+IMAGE_PROJECTION[3]+"=? OR "+IMAGE_PROJECTION[3]+"=? ",
                        new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC");
            }else if(id == LOADER_CATEGORY){
                return new CursorLoader(getActivity(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                        IMAGE_PROJECTION[4]+">0 AND "+IMAGE_PROJECTION[0]+" like '%"+args.getString("path")+"%'",
                        null, IMAGE_PROJECTION[2] + " DESC");
            }

            return null;
        }

        private boolean fileExist(String path){
            if(!TextUtils.isEmpty(path)){
                return new File(path).exists();
            }
            return false;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                if (data.getCount() > 0) {
                    List<Image> tempImages = new ArrayList<>();
                    data.moveToFirst();
                    do{
                        String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                        String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                        long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        Image image = null;
                        if (fileExist(path)) {
                            image = new Image(path, name, dateTime);
                            tempImages.add(image);
                        }
//                        if( !hasFolderGened ) {
//                            // 获取文件夹名称
//                            File folderFile = new File(path).getParentFile();
//                            if(folderFile != null && folderFile.exists()){
//                                String fp = folderFile.getAbsolutePath();
//                                Folder f = getFolderByPath(fp);
//                                if(f == null){
//                                    Folder folder = new Folder();
//                                    folder.name = folderFile.getName();
//                                    folder.path = fp;
//                                    folder.cover = image;
//                                    List<Image> imageList = new ArrayList<>();
//                                    imageList.add(image);
//                                    folder.images = imageList;
//                                    mResultFolder.add(folder);
//                                }else {
//                                    f.images.add(image);
//                                }
//                            }
//                        }

                    }while(data.moveToNext());

                    images.clear();
                    images.addAll(tempImages);
                    imageAdapter.notifyDataSetChanged();
//                    // 设定默认选择
//                    if(resultList != null && resultList.size()>0){
//                        mImageAdapter.setDefaultSelected(resultList);
//                    }
//
//                    if(!hasFolderGened) {
//                        mFolderAdapter.setData(mResultFolder);
//                        hasFolderGened = true;
//                    }

                }
//                data.close();
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

}
